<template>
    <div>
        <Modal
                v-model="modal"
                title="添加排课"
                :closable="false"
                :mask-closable="false">
            <Form
                    ref="formValidate"
                    :model="formItem"
                    :rules="ruleValidate"
                    :label-width="80">
                <FormItem label="日期" prop="day">
                    <Select v-model="formItem.day">
                        <Option v-for="item in dayList" :value="item" :key="item">{{item}}</Option>
                    </Select>
                </FormItem>
                <FormItem label="时间段" prop="time">
                    <TimePicker v-model="formItem.time"
                                format="HH:mm"
                                type="timerange"
                                placement="bottom-end"
                                placeholder="上课时间段"
                    ></TimePicker>
                </FormItem>
                <FormItem label="教室" prop="room">
                    <Select v-model="formItem.room">
                        <Option v-for="item in roomList" :value="item.name" :key="item.name">
                            {{item.name}} {{item.remark}}
                        </Option>
                    </Select>
                </FormItem>
                <FormItem label="老师" prop="teacherId">
                    <Select v-model="formItem.teacherId" filterable @on-change="changeTeacher">
                        <Option v-for="item in teacherList" :value="item.id" :key="item.id">{{item.name}}</Option>
                    </Select>
                </FormItem>
                <FormItem label="课程" prop="course">
                    <Select v-model="formItem.course">
                        <Option v-for="item in courseList" :value="item" :key="item">
                            {{item}}
                        </Option>
                    </Select>
                </FormItem>
                <FormItem label="年级" prop="grade">
                    <Select v-model="formItem.grade">
                        <Option v-for="item in gradeList" :value="item.name" :key="item.name">
                            {{item.name}} {{item.remark}}
                        </Option>
                    </Select>
                </FormItem>
                <FormItem label="课程类型" prop="feather">
                    <Select v-model="formItem.feather">
                        <Option v-for="item in featherList" :value="item.name" :key="item.name">
                            {{item.name}} {{item.remark}}
                        </Option>
                    </Select>
                </FormItem>
                <FormItem label="学生" prop="studentIds">
                    <Select v-model="formItem.studentIds" multiple @on-open-change="searchCurricula">
                        <Option v-for="item in curriculaList" :value="item.id" :key="item.id">
                            {{item.studentName}} 剩余课时
                            {{Number(item.totalPeriod)+Number(item.giftPeriod)-Number(item.usedPeriod)}}小时
                        </Option>
                    </Select>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="text" size="large" @click="cancel">取消</Button>
                <Button type="primary" size="large" @click="submit('formValidate')" v-no-more-click>确定</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
    import {getWeek} from "../request/utils"

    export default {
        name: "CalendarAddForm",
        data() {
            return {
                course: '',
                formItem: {
                    id: '',
                    day: '',
                    time: '',
                    room: '',
                    teacherId: '',
                    grade: '',
                    feather: '',
                    course: '',
                    studentIds: '' //学生报名的课程
                },
                dayList: [],
                curriculaList: [],
                courseList: [],
                roomList: [],    //教室列表
                gradeList: [],   //年级列表
                featherList: [], //班级类型列表
                teacherList: [], //老师列表
                ruleValidate: {
                    day: [{required: true, message: '日期不能为空', trigger: 'change'}],
                    room: [{required: true, message: '教室不能为空', trigger: 'change'}],
                    grade: [{required: true, message: '年级不能为空', trigger: 'change'}],
                    feather: [{required: true, message: '课程类型不能为空', trigger: 'change'}],
                    teacherId: [{required: true, type: 'number', message: '老师不能为空', trigger: 'change'}],
                }
            }
        },
        created() {
            this.getWeekList();
            this.getOptionList();
        },
        props: ['modal', 'modify'],
        watch: {
            modify: async function () {
                this.formItem = {...this.modify};
                if (this.modify.time != null) {
                    this.formItem.time = this.formItem.time.split(',')
                    let studentIds = []
                    if (this.formItem.studentIds != null) { //存在
                        this.modify.studentIds.split(',').forEach(e => {
                            studentIds.push(Number(e));
                        })
                    }
                    if (this.formItem.teacherId != '') {
                        this.changeTeacher(this.formItem.teacherId)
                    }
                    this.getCurriculaList();
                    setTimeout(() => {
                        this.formItem.studentIds = studentIds;
                    }, 500)
                }
            },
            modal: function () {
                this.$refs['formValidate'].resetFields();
            }
        },
        methods: {
            //获取当周时间
            getWeekList() {
                this.dayList = [];
                for (let i = 0; i > -14; i--) {
                    this.dayList.push(getWeek(i))
                }
            },
            //获取老师列表
            getTeachers() {
                this.$api.userGetAll({roleIds: 1}).then(res => {
                    this.teacherList = res;
                })
            },
            //搜索报名学生
            searchCurricula(flag) {
                if (flag) {
                    this.getCurriculaList();
                }
            },
            //获取报名学生列表
            getCurriculaList() {
                if (null == this.formItem.teacherId || '' == this.formItem.teacherId) {
                    this.$Message.error("请先选择科任老师")
                } else if (null == this.formItem.course || '' == this.formItem.course) {
                    this.$Message.error("请先添加科任老的课程")
                } else if (null == this.formItem.feather || '' == this.formItem.feather) {
                    this.$Message.error("请先选择班级类型")
                } else {
                    this.$api.curriculaList({
                        teacherId: this.formItem.teacherId,
                        course: this.formItem.course,
                        feather: this.formItem.feather
                    }).then(res => {
                        this.curriculaList = res;
                    })
                }
            },
            changeTeacher(id) {
                let teacher = this.teacherList.filter(function (item) {
                    return item.id == id;
                })
                if (teacher[0].course != undefined && null != teacher[0].course && teacher[0].course != '') {
                    this.courseList = teacher[0].course.split(",")
                    if (null == this.formItem.course || this.formItem.course == '')
                        this.formItem.course = this.courseList[0];
                }
            },
            submit(name) {
                this.$refs[name].validate((valid) => {
                    //判断时间
                    let flag = true;
                    let msg = '';
                    this.formItem.time.forEach(e => {
                        //时间不能空
                        if (e == '') {
                            msg = "时间段不能为空"
                            flag = false;
                        }
                    })
                    if (!flag) {
                        this.$Message.error(msg);
                    } else {
                        let time = this.formItem.time.toString();
                        //将学生集合转换成string
                        if (null != this.formItem.studentIds && this.formItem.studentIds != '') {
                            let studentIds = this.formItem.studentIds.toString();
                            delete this.formItem.studentIds;
                            this.formItem.studentIds = studentIds;
                        }
                        if (valid) {
                            if (this.formItem.studentIds.length == 0) {
                                this.formItem.studentIds = null
                            }
                            this.$api.teachingSave({
                                ...this.formItem,
                                time: time,
                            }).then(() => {
                                this.$Message.success('保存成功');
                                this.cancel()
                                this.$parent.getTable();
                            }).catch(
                            )
                        }
                    }
                })
            },
            //获取季度,年级，班级类型，教室等列表
            getOptionList() {
                this.getTeachers();
                this.getDictionaryList("grade");     //年级
                this.getDictionaryList("room");       //教室
                this.getDictionaryList("feather"); //班级类型
            },

            //获取字典列表
            getDictionaryList(parentCode) {
                this.$api.dictionaryByCode(parentCode).then(res => {
                    if (parentCode == "room") this.roomList = res;
                    else if (parentCode == "grade") {
                        this.gradeList = res;
                    } else this.featherList = res;
                })
            },
            cancel() {
                this.$parent.cancel()
            },
        }
    }
</script>

<style scoped>
</style>
